#	$Id: man.mk 1114 2010-12-07 03:21:03Z phrakt $
#	$OpenBSD: bsd.man.mk,v 1.28 2004/02/08 01:19:54 espie Exp $
#	$NetBSD: bsd.man.mk,v 1.23 1996/02/10 07:49:33 jtc Exp $
#	@(#)bsd.man.mk	5.2 (Berkeley) 5/11/90

MANTARGET?=	cat
NROFF?=		nroff -Tascii
MANLINT?=	\#

.if !target(.MAIN)
.  if exists(${.CURDIR}/../Makefile.inc)
.    include "${.CURDIR}/../Makefile.inc"
.  endif

.MAIN: all
.endif

.SUFFIXES: .1 .2 .3 .3p .4 .5 .6 .7 .8 .9 \
	.cat1 .cat2 .cat3 .cat3p .cat4 .cat5 .cat6 .cat7 .cat8 .cat9

.9.cat9 .8.cat8 .7.cat7 .6.cat6 .5.cat5 .4.cat4 .3p.cat3p .3.cat3 .2.cat2 .1.cat1:
	@echo "${NROFF} -mandoc ${.IMPSRC} > ${.TARGET}"
	@${MANLINT} ${.IMPSRC}
	@${NROFF} -mandoc ${.IMPSRC} > ${.TARGET} || (rm -f ${.TARGET}; false)



.if defined(MAN) && !empty(MAN) && !defined(MANALL)

MANALL=		${MAN:C/.([1-9])$/.cat\1/g}
#MANALL=	${MAN:S/.1$/.cat1/g:S/.2$/.cat2/g:S/.3$/.cat3/g:S/.3p$/.cat3p/g:S/.4$/.cat4/g:S/.5$/.cat5/g:S/.6$/.cat6/g:S/.7$/7/g:S/.8$/$s8/g:S/.9$/$s9/g}

.endif

MINSTALL=  ${INSTALL} ${INSTALL_COPY} -o ${MANOWN} -g ${MANGRP} -m ${MANMODE}

.if defined(MANZ)
# chown and chmod are done afterward automatically
MCOMPRESS=	gzip -cf
MCOMPRESSSUFFIX= .gz
.endif

.if defined(MANSUBDIR)
# Add / so that we don't have to specify it. Better arch -> MANSUBDIR mapping
MANSUBDIR:=${MANSUBDIR:S,^,/,}
.else
# XXX MANSUBDIR must be non empty for the mlink loops to work
MANSUBDIR=''
.endif

.if !defined(MCOMPRESS) || empty(MCOMPRESS)
install_manpage_fragment= \
	echo ${MINSTALL} $$page $$instpage; \
	${MINSTALL} $$page $$instpage
.else
install_manpage_fragment= \
	rm -f $$instpage; \
	echo ${MCOMPRESS} $$page \> $$instpage; \
	${MCOMPRESS} $$page > $$instpage; \
	chown ${MANOWN}:${MANGRP} $$instpage; \
	chmod ${MANMODE} $$instpage
.endif

maninstall: ${MANALL}
.if defined(MANALL)
	@for page in ${MANALL}; do \
		set -- ${MANSUBDIR}; \
		subdir=$$1; \
		dir=${DESTDIR}${MANDIR}$${page##*.cat}; \
		base=$${page##*/}; \
		instpage=$${dir}$${subdir}/$${base%.*}.0${MCOMPRESSSUFFIX}; \
		${install_manpage_fragment}; \
		while test $$# -ge 2; do \
			shift; \
			extra=$${dir}$$1/$${base%.*}.0${MCOMPRESSSUFFIX}; \
			echo $$extra -\> $$instpage; \
			ln -f $$instpage $$extra; \
		done; \
	done
.endif

.if defined(MLINKS) && !empty(MLINKS)
.  for sub in ${MANSUBDIR}
.     for lnk file in ${MLINKS}
	@l=${DESTDIR}${MANDIR}${lnk:E}${sub}/${lnk:R}.0${MCOMPRESSSUFFIX}; \
	t=${DESTDIR}${MANDIR}${file:E}${sub}/${file:R}.0${MCOMPRESSSUFFIX}; \
	echo $$t -\> $$l; \
	rm -f $$t; ln $$l $$t;
.     endfor
.  endfor
.endif

.if defined(MANALL) && !defined(MANLOCALBUILD)
all: ${MANALL}

cleandir: cleanman
cleanman:
	rm -f ${MANALL}
.endif
